package com.pan.studentmaster;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageButton;

public class PageActivity extends Activity implements OnClickListener, TurnableListener, OnTouchListener {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_page);
		_backPage = (Turnable)findViewById(R.id.backPage);
		_backPage.setListener(this);
		_page = (SVGPage)findViewById(R.id.container);
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			_bookId = extras.getInt("BOOK");
			Log.i("PAGE", "Started PageActivity for book " + _bookId);
			Cursor cursor = DB.instance().getBookInfo(_bookId);
			_bookName = cursor.getString(cursor.getColumnIndex(DB.BOOK._TITLE));
			_bookSubName = cursor.getString(cursor.getColumnIndex(DB.BOOK._SUBTITLE));
			_pageId = cursor.getInt(cursor.getColumnIndex(DB.BOOK._PAGE));
			_pagesCount = cursor.getInt(cursor.getColumnIndex(DB.BOOK._PAGES));
			cursor.close();
			Bitmap bmp = BookMaster.instance().getBitmap(_bookId, _pageId);
			BitmapDrawable drawable = new BitmapDrawable(Main.instance().getResources(), bmp);
			_backPage.setBackground(drawable);
			_page.load(_bookId, _pageId);
		}
		_prevButton = (ImageButton)findViewById(R.id.imgBtnPrev);
		_prevButton.setOnClickListener(this);
		if(_pageId == 0)
			_prevButton.setVisibility(View.INVISIBLE);
		_nextButton = (ImageButton)findViewById(R.id.imgBtnNext);
		_nextButton.setOnClickListener(this);
		if(_pageId == _pagesCount)
			_nextButton.setVisibility(View.INVISIBLE);
		FlingCapturer flingCapturer = new FlingCapturer();
		_gestureDetector = new GestureDetector(this, flingCapturer);
		_page.setOnTouchListener(this);
		showTitle();
		// reset the stationary when opening a page
		Stationary.setCurrentStationary(Stationary.PENCIL * Stationary.M + Stationary.P_HB);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_page, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			Intent i = new Intent().setClass(this, Pref.class);
			startActivity(i);
			return true;
		}
		else if(id == R.id.action_stationary) {
			if(_stationaryDialog == null) {
				_stationaryDialog = new StationaryDialog(this, item);
				_stationaryDialog.setOwnerActivity(this);
			}
			_stationaryDialog.show();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		if(_backPage.turning())
			return;
		if(v.getId() == R.id.imgBtnPrev) {
			if(_pageId > 0) {
				// _backPage caches current page, previous page, and next page
				// try to utilize this page instead of reading PDF every time
				Bitmap prev = _backPage.getPrevBitmap();
				if(prev == null)
					prev = BookMaster.instance().getBitmap(_bookId, _pageId - 1);
				if(prev != null)
					_backPage.turnBackward(prev);
			}
		}
		else if(v.getId() == R.id.imgBtnNext) {
			if(_pageId < _pagesCount) {
				Bitmap next = _backPage.getNextBitmap();
				if(next == null)
					next = BookMaster.instance().getBitmap(_bookId, _pageId + 1);
				if(next != null)
					_backPage.turnForward(next);
			}
		}
	}
	
	@Override
	public void onStop() {
		_page.save();
		super.onStop();
	}
	
	@Override
	public void onTurnStart(Turnable t) {
		_page.save();
		_page.reset();
	}

	@Override
	public void onTurnFinish(Turnable t) {
		if(_backPage.turningForward()) {
			++_pageId;
			if(_pageId == 1)
				_prevButton.setVisibility(View.VISIBLE);
			else if(_pageId == _pagesCount)
				_nextButton.setVisibility(View.INVISIBLE);
		}
		else if(_backPage.turningBackward()) {
			--_pageId;
			if(_pageId == 0)
				_prevButton.setVisibility(View.INVISIBLE);
			else if(_pageId == _pagesCount - 1)
				_nextButton.setVisibility(View.VISIBLE);
		}
		_page.load(_bookId, _pageId);
		_page.postInvalidate();
		DB.instance().setBookPage(_bookId, _pageId);
		showTitle();
	}
	
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if(_gestureDetector.onTouchEvent(event)) {
			_page.cancelCurrentPath();
			return true;
		}
		return false;
	}
	
	// private
	
	private int					_bookId;
	private int					_pageId;
	private String				_bookName;
	private String				_bookSubName;
	private SVGPage				_page;
	private Turnable			_backPage;
	private int					_pagesCount;
	private StationaryDialog	_stationaryDialog = null;
	private ImageButton			_prevButton;
	private ImageButton			_nextButton;
	private GestureDetector		_gestureDetector;
	
	private void showTitle() {
		setTitle(_bookName + "/" + _bookSubName + "(" + _pageId + "/" + _pagesCount + ")");
	}
	
	private class FlingCapturer extends GestureDetector.SimpleOnGestureListener {
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float vx, float vy) {
			Log.i("FLING", e1.toString() + "," + e2.toString() + " " + (int)vx + "," + (int)vy);
			SharedPreferences prefs = Main.instance().getSharedPreferences(Main.APP_NAME, Context.MODE_PRIVATE);
			int velocity = prefs.getInt(Pref.FLING_SENSITIVITY, 2000);
			int delta = velocity / 10;
			// use action1 to start detection a fling
			// so change of velocity won't change our detection
			// -- this is because some of the motion is already used in SVG
			int action1 = e1.getAction() & MotionEvent.ACTION_MASK;
			if(action1 == MotionEvent.ACTION_DOWN) {
				if(vx < -velocity && e1.getX() - e2.getX() > delta)
					_state = FLING_LEFT;
				else if(vx > velocity && e2.getX() - e1.getX() > delta)
					_state = FLING_RIGHT;
			}
			// use action2 to finish a fling and start turning page
			int action2 = e2.getAction() & MotionEvent.ACTION_MASK;
			if(action2 == MotionEvent.ACTION_UP) {
				if(_state == FLING_RIGHT) {
					_state = FLING_NONE;
					onClick(_prevButton);
					return true;
				}
				else if(_state == FLING_LEFT) {
					_state = FLING_NONE;
					onClick(_nextButton);
					return true;
				}
			}
			// if we've detected a fling, return true to stop SVG
			return _state != FLING_NONE;
		}
		static final private int	FLING_NONE = 0;
		static final private int	FLING_LEFT = 1;
		static final private int	FLING_RIGHT = 2;
		private int					_state = FLING_NONE;
	}

}
